package com.ecode.ecny.advice;

import com.ecode.ecny.exception.ExpCode;
import com.ecode.ecny.uitl.DateTimeUtil;
import com.ecode.ecny.base.RspHead;
import com.ecode.ecny.base.TxnStatus;
import com.ecode.ecny.dto.BaseRspDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @ClassName ErrorHandlerAdvice
 * @Author mjlft
 * @Date 2021/8/14 11:40
 * @Version 1.0
 * @Description 错误处理
 */
@RestControllerAdvice
public class ErrorHandlerAdvice {
    private static final Logger logger = LoggerFactory.getLogger(ErrorHandlerAdvice.class);

    /**
     * 系统未知错误
     *
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public BaseRspDTO errorHandler(Exception ex) {
        //异常日志入库
        RspHead rspHead = new RspHead();
        //APIResponse是项目中对外统一的出口封装，可以根据自身项目的需求做相应更改
        if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException exx = (MethodArgumentNotValidException) ex;
            logger.error("捕获到Exception异常:{}", exx.getBindingResult());

            rspHead.setRetCode(ExpCode.PARAM_001.getCode());
            rspHead.setRetMsg(exx.getFieldError().getField() + ":" + exx.getAllErrors().get(0).getDefaultMessage());
            rspHead.setRetDate(DateTimeUtil.getCurrentDate());
            rspHead.setRetTime(DateTimeUtil.getCurrentTime());
            rspHead.setTrnStatus(TxnStatus.EXPT);
        } else {
            logger.error("捕获到Exception异常:{}", ex);
            rspHead = RspHead.createHead(ex);
        }
        return new BaseRspDTO(rspHead);
    }
}
